/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.pig4cloud.common.oss.service;


import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.SimplifiedObjectMeta;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

import java.io.InputStream;
import java.net.URL;
import java.util.Date;

/**
 * oss 交互类
 *
 * @author lengleng
 */
@RequiredArgsConstructor
public class OssTemplate implements InitializingBean {
	private final String endpoint;
	private final String accessKeyId ;
	private final String accessKeySecret ;
	private OSSClient client;



	/**
	 * 上传文件
	 *
	 * @param bucketName bucket名称
	 * @param objectName 文件名称
	 * @param stream     文件流
	 * @throws Exception https://docs.minio.io/cn/java-client-api-reference.html#putObject
	 */
	public void putObject(String bucketName, String objectName, InputStream stream, ObjectMetadata metadata){
		client.putObject(bucketName, objectName, stream, metadata);
	}

	public URL generatePresignedUrl(String bucketName, String objectName, Date expiration) {
		return client.generatePresignedUrl(bucketName, objectName, expiration);
	}

	public SimplifiedObjectMeta getSimplifiedObjectMeta(String bucketName, String objectName){
		return  client.getSimplifiedObjectMeta(bucketName, objectName);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		Assert.hasText(endpoint, "OSS url 为空");
		Assert.hasText(accessKeyId , "OSS accessKey为空");
		Assert.hasText(accessKeySecret , "OSS secretKey为空");
		this.client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
	}


}
